package com.example.shiwu.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.example.shiwu.GpsAddActivity;
import com.example.shiwu.GpsDetailsActivity;
import com.example.shiwu.R;
import com.example.shiwu.SendReceiveImgDetailsActivity;
import com.example.shiwu.GpsListActivity;
import com.example.shiwu.db.model.BoxEight;
import com.example.shiwu.db.model.BoxFive;
import com.example.shiwu.db.model.BoxFour;
import com.example.shiwu.db.model.BoxNine;
import com.example.shiwu.db.model.BoxOne;
import com.example.shiwu.db.model.BoxSeven;
import com.example.shiwu.db.model.BoxSix;
import com.example.shiwu.db.model.BoxTen;
import com.example.shiwu.db.model.BoxThree;
import com.example.shiwu.db.model.BoxTwo;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.model.Sends;
import com.example.shiwu.db.vo.GpsVo;
import com.example.shiwu.service.BoxEightService;
import com.example.shiwu.service.BoxFiveService;
import com.example.shiwu.service.BoxFourService;
import com.example.shiwu.service.BoxNineService;
import com.example.shiwu.service.BoxOneService;
import com.example.shiwu.service.BoxSevenService;
import com.example.shiwu.service.BoxSixService;
import com.example.shiwu.service.BoxTenService;
import com.example.shiwu.service.BoxThreeService;
import com.example.shiwu.service.BoxTwoService;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.service.SendsService;
import com.example.shiwu.util.BoxUtil;
import com.example.shiwu.util.DateUtils;
import com.example.shiwu.util.FileDownUtil;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class GpsAdapter extends BaseAdapter implements View.OnClickListener{

    private GpsListActivity mContext;
    private int resourceId;
    public boolean flage = false;
    private List<GpsVo> listItems;
    private LayoutInflater mInflater;
    private String[] myModaData;
    private Integer checkBoxIDList;            //存储checkBox的值
    private MyClickListener mListener,rListener;
    private BoxOneService boxOneService;
    private BoxTwoService boxTwoService;
    private BoxThreeService boxThreeService;
    private BoxFourService boxFourService;
    private BoxFiveService boxFiveService;
    private BoxSixService boxSixService;
    private BoxSevenService boxSevenService;
    private BoxEightService boxEightService;
    private BoxNineService boxNineService;
    private BoxTenService boxTenService;
    private ItemsService itemsService;
    //自定义接口，用于回调按钮点击事件到Activity
    public interface MyClickListener{
        public void clickListener(View v);
        boolean clickRemoveListener(int position);
    }



    public GpsAdapter(GpsListActivity mContext, List<GpsVo> listItems, int resource, String[] modeData,
                      MyClickListener listener) {
        this.resourceId = resource;
        this.mContext = mContext;
        this.listItems = listItems;
        this.myModaData = modeData;
        this.mListener = listener;
        this.rListener = listener;
        initService();
    }
    public void cleckAll() {
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;
        final ViewHolder viewHolder;
        if (convertView == null) {
            view = LayoutInflater.from(parent.getContext()).inflate(resourceId, parent, false);
            viewHolder = new ViewHolder(view, position);
            viewHolder.gps_item_id.setText(String.valueOf(listItems.get(position).getItemId()));
            viewHolder.device_id.setText(listItems.get(position).getDeviceId());
            viewHolder.gps_items_name.setText(listItems.get(position).getName());
            viewHolder.gps_operator.setText(String.valueOf(listItems.get(position).getOperator()));
            viewHolder.gps_items_createTime.setText(listItems.get(position).getCreateTime());
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (GpsAdapter.ViewHolder) view.getTag();
            viewHolder.gps_item_id.setText(String.valueOf(listItems.get(position).getItemId()));
            viewHolder.device_id.setText(listItems.get(position).getDeviceId());
            viewHolder.gps_items_name.setText(listItems.get(position).getName());
            viewHolder.gps_operator.setText(String.valueOf(listItems.get(position).getOperator()));
            viewHolder.gps_items_createTime.setText(listItems.get(position).getCreateTime());
        }


        viewHolder.detailsSub.setOnClickListener(new View.OnClickListener() {//详情
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, GpsDetailsActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //Integer sId = Integer.parseInt(listItems.get(position).getId());
                Integer itemId = listItems.get(position).getItemId();
                intent.putExtra("id",String.valueOf(itemId));
                mContext.startActivity(intent);
            }
        });

        viewHolder.delSb.setOnClickListener(new View.OnClickListener() {//删除
            @Override
            public void onClick(View v) {
                System.out.println("id =================================== " + v.getId());
                //点击删除按钮之后，给出dialog提示
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                builder.setTitle("确认删除?");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("id =================================== " + position);
                        System.out.println("——————————————删除——————————————————");
                        //Integer sId = Integer.parseInt(listItems.get(position).getId());
                        Integer itemId = listItems.get(position).getItemId();
                        BoxUtil.updateBox(String.valueOf(itemId));
                        mContext.updataData();
                    }
                });
                builder.show();
            }
        });

        viewHolder.delSb.setOnClickListener(new View.OnClickListener() {//删除
            @Override
            public void onClick(View v) {
                System.out.println("id =================================== " + v.getId());
                //点击删除按钮之后，给出dialog提示
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                builder.setTitle("确认删除?");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("id =================================== " + position);
                        System.out.println("——————————————删除——————————————————");
                        //Integer sId = Integer.parseInt(listItems.get(position).getId());
                        Integer itemId = listItems.get(position).getItemId();
                        BoxUtil.updateBox(String.valueOf(itemId));
                        mContext.updataData();
                    }
                });
                builder.show();
            }
        });

        //获取复选框选中状态改变事件进行增删改
        viewHolder.exportSb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("id =================================== " + v.getId());
                Integer itemId = listItems.get(position).getItemId();
                Boolean boo = exportData(itemId);
            }
        });

        return view;
    }
    private boolean exportData(Integer itemId){
        List<Object> list = new ArrayList<>();
        String itemName = itemsService.getItems(new Items(itemId)).get(0).getName();
        String fileName = itemName+"_GPS_"+DateUtils.parseYmdDate()+".txt";
        List<BoxOne> boxOne = boxOneService.getBoxOne(new BoxOne());
        List<BoxTwo> boxTwo = boxTwoService.getBoxTwo(new BoxTwo());
        List<BoxThree> boxThree = boxThreeService.getBoxThree(new BoxThree());
        List<BoxFour> boxFour = boxFourService.getBoxFour(new BoxFour());
        List<BoxFive> boxFive = boxFiveService.getBoxFive(new BoxFive());
        List<BoxSix> boxSix = boxSixService.getBoxSix(new BoxSix());
        List<BoxSeven> boxSeven = boxSevenService.getBoxSeven(new BoxSeven());
        List<BoxEight> boxEight = boxEightService.getBoxEight(new BoxEight());
        List<BoxNine> boxNine = boxNineService.getBoxNine(new BoxNine());
        List<BoxTen> boxTen = boxTenService.getBoxTen(new BoxTen());

        if(boxOne.size() >0){
            list.add(boxOne.get(0));
        }

        if(boxTwo.size() >0){
            list.add(boxTwo.get(0));
        }

        if(boxThree.size() >0){
            list.add(boxThree.get(0));
        }

        if(boxFour.size() >0){
            list.add(boxFour.get(0));
        }

        if(boxFive.size() >0){
            list.add(boxFive.get(0));
        }

        if(boxSix.size() >0){
            list.add(boxSix.get(0));
        }

        if(boxSeven.size() >0){
            list.add(boxSeven.get(0));
        }

        if(boxEight.size() >0){
            list.add(boxEight.get(0));
        }

        if(boxNine.size() >0){
            list.add(boxNine.get(0));
        }

        if(boxTen.size() >0){
            list.add(boxTen.get(0));
        }

        //writeObjectToExternalStorage(mContext,list,fileName,itemName);
        Boolean bool2 = FileDownUtil.saveWithMediaStore(mContext,list,fileName,itemName);
        if(bool2){
            Toast.makeText(mContext, "文件已保存到 Download"+"/shiwu/"+itemName+" 目录", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(mContext, "导出失败！", Toast.LENGTH_SHORT).show();
        }
        return true;
    }
    private void initService(){
        boxOneService = new BoxOneService();
        boxTwoService = new BoxTwoService();
        boxThreeService = new BoxThreeService();
        boxFourService = new BoxFourService();
        boxFiveService = new BoxFiveService();
        boxSixService = new BoxSixService();
        boxSevenService = new BoxSevenService();
        boxEightService = new BoxEightService();
        boxNineService = new BoxNineService();
        boxTenService = new BoxTenService();
        itemsService = new ItemsService();
    }
    private void writeObjectToExternalStorage(Context context, List<Object> list, String fileName,String itemName) {
// 获取下载目录
        File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS+"/shiwu/"+itemName+"/");
        Gson gson = new Gson();
        String jsonString = gson.toJson(list);
        // 获取外部存储目录（公共文档目录）
        File file = new File(downloadsDir, fileName);
        //for (int i = 0; i < list.size(); i++) {
            try (FileWriter writer = new FileWriter(file)) {
                // 写入对象
                writer.write(jsonString);
                Toast.makeText(context, "文件已保存到: " + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
                Log.d("文件已保存到: ",file.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(context, "保存失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                Log.d("文件保存失败: ",e.getMessage());
            }
        //}

    }

    @Override
    public int getCount() {
        return listItems.size();
    }

    @Override
    public Object getItem(int position) {
        return listItems.get(position);
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

    //响应按钮点击事件,调用子定义接口，并传入View
    @Override
    public void onClick(View v) {
        mListener.clickListener(v);
    }
    class ViewHolder {
        public TextView detailsSub,delSb, device_id,gps_items_name, gps_operator,gps_items_createTime,gps_item_id,exportSb;
        public CheckBox gps_checkbox;

        public ViewHolder(View view, int position) {
            device_id = view.findViewById(R.id.device_id_val);
            gps_item_id = view.findViewById(R.id.gps_item_id);
            gps_items_name = view.findViewById(R.id.gps_items_name_val);
            gps_operator = view.findViewById(R.id.gps_operator_val);
            gps_items_createTime = view.findViewById(R.id.gps_items_createTime_val);
            detailsSub = view.findViewById(R.id.gps_items_details_sb);
            delSb = view.findViewById(R.id.gps_items_del_sb);
            exportSb = view.findViewById(R.id.gps_items_export_sb);
            gps_checkbox = view.findViewById(R.id.gps_list_items_checkbox);
        }

    }

}
